﻿'***********************************************************************
'Magic Chimney Imp (MCI)
'Copyright (C) 2011  David Frendin (david.frendin@gmail.com)
'
'This program is free software: you can redistribute it and/or modify
'it under the terms of the GNU General Public License as published by
'the Free Software Foundation, either version 3 of the License, or
'(at your option) any later version.
'
'This program is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'GNU General Public License for more details.
'
'You should have received a copy of the GNU General Public License
'along with this program.  If not, see <http://www.gnu.org/licenses/>.
'***********************************************************************
Imports System.Net
Imports System.IO
Imports System.Text

Public Class OracleSetImporter

#Region " Structures "
    Public Structure CardStruct
        Dim Name As String
        Dim Cost As String
        Dim Type As String
        Dim PT As String
        Dim Rules As String
        Dim Rarity As String
        Dim MultiverseId As String
    End Structure

    Public Structure ExportSetStruct
        Dim SetName As String
        Dim FileName As String
    End Structure

    Public Structure ThreadQueueStruct
        Dim ExportSet As ExportSetStruct
        Dim Thread As Threading.Thread
    End Structure
#End Region

#Region " Delegates "
    Delegate Sub SetImportButtonEnabledStatusDelegate(ByVal Value As Boolean)
    Delegate Sub SetProgressBarStatusDelegate(ByVal Value As Integer, ByVal Max As Integer, ByVal Min As Integer)
    Delegate Sub SetInformationBoxDelegate(ByVal Value As String)
    Delegate Sub SetToolstripTextDelegate(ByVal Value As String)
#End Region

    Public Shared Function GetPage(ByVal pageUrl As String) As String
        Dim s As String = String.Empty
        Dim request As HttpWebRequest = WebRequest.Create(pageUrl)
        Dim response As HttpWebResponse = request.GetResponse()
        Using reader As StreamReader = New StreamReader(response.GetResponseStream())
            s = reader.ReadToEnd()
        End Using
        Return s
    End Function

    Public Shared Sub SaveSet(ByVal state As Object)
        Dim StObj As ExportSetStruct
        StObj = CType(state, ExportSetStruct)
        Dim setName As String = StObj.SetName
        Dim fileName As String = StObj.FileName

        Try
            Dim a As New ArrayList
            Dim page As String = OracleSetImporter.GetPage("http://gatherer.wizards.com/Pages/Search/Default.aspx?output=spoiler&method=text&set=[%22" & Uri.EscapeUriString(setName) & "%22]&special=true")
            Dim startpos As Integer = InStr(page, "<div class=""textspoiler"">")
            page = Mid(page, startpos)
            Dim endpos As Integer = InStr(page, "<div class=""clear""></div>")
            page = Mid(page, 1, endpos - 1)
            Dim nendpos As Integer = InStrRev(page, "</div>")
            page = Mid(page, 1, nendpos - 1)

            page = Replace(page, "&nbsp;", " ")

            Dim xmldoc As New Xml.XmlDocument
            xmldoc.LoadXml(page)


            Dim spoilertablenode As Xml.XmlNode = xmldoc.SelectSingleNode("/div/table")
            Dim nodes As Xml.XmlNodeList = spoilertablenode.SelectNodes("tr")
            For i As Integer = 0 To nodes.Count - 1 Step 7
                Dim newCard As New CardStruct
                With newCard
                    Try
                        Dim raw As String = GetRawFromNodePair(nodes(i))
                        Dim begin As Integer = InStr(raw, "multiverseid=")
                        raw = Mid(raw, begin + 13)
                        Dim send As Integer = InStr(raw, """")
                        raw = Mid(raw, 1, send - 1)

                        .MultiverseId = FixWhite(raw)
                    Catch
                        'Exception - unknown MultiverseId
                        .MultiverseId = "unknown"
                    End Try
                    .Name = FixWhite(GetFromNodePair(nodes(i)))
                    .Cost = FixWhite(GetFromNodePair(nodes(i + 1)))
                    .Type = FixWhite(GetFromNodePair(nodes(i + 2)))
                    .PT = FixWhite(GetFromNodePair(nodes(i + 3)))
                    .Rules = FixWhite(GetFromNodePair(nodes(i + 4)))
                    Try
                        .Rarity = FixWhite(GetFromNodePair(nodes(i + 5)))
                    Catch
                        .Rarity = "unknown"
                    End Try
                End With
                a.Add(newCard)
            Next

            Dim sb As New StringBuilder
            'sb.AppendLine("<set name=""" & setName & """ count=""" & nodes.Count / 7 & """>")
            For Each cs As CardStruct In a

                sb.Append("<card>")
                sb.Append(String.Concat("<multiverseid>", cs.MultiverseId, "</multiverseid>"))
                sb.Append(String.Concat("<name>", cs.Name, "</name>"))
                sb.Append(String.Concat("<cost>", cs.Cost, "</cost>"))
                sb.Append(String.Concat("<type>", cs.Type, "</type>"))
                sb.Append(String.Concat("<pt>", cs.PT, "</pt>"))
                sb.Append(String.Concat("<rules>", cs.Rules, "</rules>"))
                sb.Append(String.Concat("<rarity>", cs.Rarity, "</rarity>"))
                sb.Append(String.Concat("<set>", setName, "</set>"))
                sb.AppendLine("</card>")
            Next
            'sb.AppendLine("</set>")

            Using sw As New IO.StreamWriter(fileName)
                sw.Write(sb.ToString)
            End Using
        Catch ex As Exception
            MsgBox("Could not import " & setName & ": " & ex.Message)
        End Try
    End Sub

    Private Shared Function FixWhite(ByVal str As String) As String
        str = Replace(str, vbCrLf, "")
        str = Trim(str)
        Return str
    End Function


    Private Shared Function GetFromNodePair(ByVal n As Xml.XmlNode) As String
        Dim tdnodes As Xml.XmlNodeList = n.SelectNodes("td")
        Dim tdnode As Xml.XmlNode = tdnodes(1)
        Return tdnode.InnerText
    End Function

    Private Shared Function GetRawFromNodePair(ByVal n As Xml.XmlNode) As String
        Dim tdnodes As Xml.XmlNodeList = n.SelectNodes("td")
        Dim tdnode As Xml.XmlNode = tdnodes(1)
        Return tdnode.InnerXml
    End Function

End Class